package com.corticon.client.web;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.context.MessageSource;

import com.corticon.client.model.GeneralMessage;
import com.corticon.client.util.MapUtils;

/**
 * @author Lifan Yang
 */
public abstract class BaseController {
	protected static Log corticonlogger = LogFactory.getLog("corticon");
	protected static Log performancelogger = LogFactory.getLog("performance");
    protected String requestSuffix = ".html";

    // Message Constants
    protected String[] defaultMessageKeys = {"message"};
    protected final String DEFAULT_MESSAGE_KEY = "message";

    // Error Constants
    protected String errorsViewName = "errors";
    protected final String ERROR_MESSAGE_KEY = "errors";
    protected String entityNotFoundViewName = "entityNotFound";
    protected String redirectPrefix = "redirect:";
    // Other Constants
    protected String PAGER_NAME = "pager";
    protected String LAST_RESPONSE_ID = "0";
    protected String LAST_RESPONSE_PIX = "dialogInstanceId";    

    // Other Resources
    @Resource
    protected MessageSource messageSource;
    // Message
    protected static final String publicFoundMessage = "public.found";
    protected static final String publicNotFoundMessage = "public.not.found";
    protected static final String E00001 = "Error on casting String to JSON";
    protected static final String E00002 = "Not enough parameter";// no Mode parameter
    protected static final String E00003 = "Does not connect to Rule Service";
    protected static final String E00004 = "Error on calling Rule Service";
    protected static final String E00005 = "NullPointerException";
    protected static final String E00006 = "Error on connect to DB";
    protected static final String E00007 = "The Results More Than one. Results is more than one.";
    protected static final String E00008 = "No Result matched the entered criteria.";
    protected static final String E00009 = "Error on casting Data type";
    protected static final String E00010 = "No result is finded.";
    /**
     * Get the default view name according to the request path.
     *
     * @param request
     * @return
     */
    protected String getViewNameByRequestURI(HttpServletRequest request) {

        String viewName = "";

        String contextPath = request.getContextPath();
        String requestURI = request.getRequestURI();

        // Remove the contextPath from the requestURI.
        requestURI = StringUtils.removeStart(requestURI, contextPath);

        // Remove the request suffix from the requestURI.
        requestURI = StringUtils.removeEnd(requestURI, requestSuffix);

        if (requestURI != null && !requestURI.equals("")) {
            if (requestURI.startsWith("/")) {
                requestURI = StringUtils.substring(requestURI, 1);
            }

            if (requestURI.endsWith("/")) {
                requestURI = requestURI.substring(0, requestURI.length() - 1);
            }

            return StringUtils.replace(requestURI, "/", ".");
        }

        return viewName;
    }

    /**
     * Get the messages from SessionScope according to the messageKeys, put
     * these messages into RequestScope. Then clean these messages from
     * SessionScope.
     *
     * @param messageKeys
     * @param request
     */
    protected void readMessages(String[] messageKeys, HttpServletRequest request) {
        for (String messageKey : messageKeys) {
            String message = (String) request.getSession().getAttribute(
                    messageKey);

            if (StringUtils.isNotBlank(message)) {
                request.setAttribute(messageKey, message);
                request.getSession().removeAttribute(messageKey);
            }
        }
    }

    /**
     * Remove messages from http session
     *
     * @param messageKeys
     * @param request
     */
    protected void cleanMessages(String[] messageKeys, HttpServletRequest request) {
        for (String messageKey : messageKeys) {
            request.getSession().removeAttribute(messageKey);
        }
    }
    protected List<GeneralMessage> checkMessage(List<GeneralMessage> messages){
    	List<GeneralMessage> newMessages = new ArrayList();
    	if (messages!=null && messages.size()>0){
    		for(int i=0;i<messages.size();i++){
    			GeneralMessage message = messages.get(i);
    			//if (message.getCode()!=null && message.getCode().indexOf(".")>0){
    				GeneralMessage newMessage = new GeneralMessage();
    				String msg ="";
    				try{
    					msg = messageSource.getMessage(message.getCode(), null,Locale.ENGLISH);
    				}catch(Exception e){
    					msg = message.getCode();
    				}
    				newMessage.setCode(msg);
    				newMessage.setQuestionId(message.getQuestionId());
    				newMessages.add(newMessage);
    			//}    			
    		}
    	}
    	return newMessages;
    }
    protected void outPutJson(String jsonObj,HttpServletResponse response){
    	PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.write(jsonObj);
			pw.flush();
		} catch (IOException e) {			
			StringWriter sw = new StringWriter();
			e.printStackTrace(new PrintWriter(sw));
			corticonlogger.error("[E00001]" + E00001 + "\n" + sw);
		}
		
    }
    protected String redirectTo403() {
        return redirectPrefix + "/403.jsp";
    }

    protected String entityNotFound() {
        return entityNotFoundViewName;
    }
}
